import React from 'react';
import PropTypes from 'prop-types';
import { gql } from '@apollo/client';
import { useQuery } from '@apollo/client';

import { turnToMinute } from '../../../../../common/timeUnitConver';
import ChartPanel from '../ChartPanel';

const QUERY_GQL = gql`
	query {
		SitePortraitMany {
			_id
			target
			result {
				result {
					warningCount
				}
			}
		}
	}
`;
export default function SitePortrait({ className, data, taskIdMap }) {
	useQuery(QUERY_GQL);

	// todo
	const total = 0;
	const initData = {};
	// const initData = data.reduce((res, item) => {
	// 	if (item.length > 0) {
	// 		const task = item[0];
	// 		const sum = item.reduce((sum, task) => {
	// 			sum += task?.result?.result?.warningCount || 0;
	// 			return sum;
	// 		}, 0);
	// 		res[task.target] = {
	// 			sum,
	// 			tasks: item,
	// 			interval: task.taskSettings.interval,
	// 		};
	// 	}
	// 	return res;
	// }, {});

	const sortData = Object.entries(initData)
		.map(([target, item]) => ({ target, ...item }))
		.sort((a, b) => {
			return turnToMinute(a.interval) - turnToMinute(b.interval);
		});

	let chartLine = [];
	const chartOtherData = [];
	sortData.forEach(({ target }) => {
		if (chartLine.length === 0 && initData[target]?.tasks?.length > 1) {
			chartLine = initData[target]?.tasks;
		} else {
			chartOtherData.push(initData[target]?.tasks || []);
		}
	});

	const chartData = chartLine.map(({ updateTime, result }) => {
		let count = result?.result?.warningCount || 0;
		chartOtherData.forEach(data => {
			data.forEach((d, idx) => {
				if (
					(d?.updateTime < updateTime &&
						data[idx + 1]?.updateTime > updateTime) ||
					data.length === idx + 1
				) {
					count += d?.result?.result?.warningCount || 0;
				}
			});
		});
		return [updateTime, count];
	});

	// const tableData = (siteData?.SitePortraitMany || [])
	// 	.map(item => {
	// 		const target = item?.target;
	// 		const sum = item?.result?.result?.warningCount || 0;
	// 		total += sum;
	// 		return {
	// 			target,
	// 			sum,
	// 			link: taskIdMap[target]._id ? `/site-portrait/${taskIdMap[target]._id}` : undefined,
	// 		};
	// 	})
	// 	.sort((a, b) => b.sum - a.sum);

	const columns = [
		{ name: 'target', label: '监测资产' },
		{ name: 'sum', label: '异常路径', width: 72 },
	];

	return (
		<ChartPanel
			key="site"
			className={className}
			title="网站画像"
			type="site"
			desc="以下数据为最近一次的网站监测结果，按异常路径数从高到低排序。"
			link="/site-portrait"
			tableData={[]}
			chartData={chartData}
			num={total}
			tooltipText="最近十次监测结果趋势图"
			numLabel="异常路径总数"
			tableColumns={columns}
			chartLabel="总资产异常路径趋势"
		/>
	);
}

SitePortrait.propTypes = {
	className: PropTypes.string,
	data: PropTypes.array,
	taskIdMap: PropTypes.object,
};
